<?php
require_once dirname(__FILE__) . '/Config.inc.php';

/**
 *
 * @author Kinmeic
 *        
 */
class Model {
	// TODO - Insert your code here
	private static $instance;
	protected $client;
	public $db;
	
	/**
	 */
	function __construct() {
		global $Config;
		
		if (isset($Config) && isset($Config['db'])) {
			
			switch ($Config['db']['type']) {
				case 'mongodb':
					$this->mongodb_conn($Config);
					break;
				case 'mysql':
					$this->mysql_conn($Config);
					break;
				default:
					exit('Fatal error: Database type does not defined in Config.inc.php.');
			}
		} else {
			exit('Fatal error: Database configuration does not found in Config.inc.php.');	
		}
	}
	
	/**
	 */
	function __destruct() {
		
		// TODO - Insert your code here
	}
	
	public static function getInstance() {
		if ( !isset(self::$instance))
		{
			self::$instance = new self;
		}
		
		return self::$instance;
	}
	
	/**
	 * 连接MongoDB
	 */
	private function mongodb_conn($config){
		$hostname = $config['db']['host'];
		$database = $config['db']['name'];
		$username = $config['db']['user'];
		$password = $config['db']['pswd'];
		
		try {
			$this->client = new MongoClient("mongodb://$hostname", array(
					'db' => $database,
					'username' => $username,
					'password' => $password
			));
			$this->db = $this->client->selectDB($database);
		} catch (Exception $e) {
			exit("Fatal error: " . $e->getCode() . ":" .$e->getMessage());
		}
	}
	
	/**
	 * 连接MySQL
	 */
	private function mysql_conn($config) {
		$hostname = $config['db']['host'];
		$database = $config['db']['name'];
		$username = $config['db']['user'];
		$password = $config['db']['pswd'];
		
		try {
			//array(PDO::ATTR_PERSISTENT => true)
			$this->db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
			$this->db->query("SET NAMES 'utf8'");
			$this->db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
		} catch (PDOException $e) {
			exit("Fatal error: " . $e->getMessage());
		}
	}
	
}
?>